#ifndef DB_H
#define DB_H

#include "exception/DbException.h"
#include "global.h"
#include "SQL.h"
#include "DbResult.h"

namespace ZY
{

    class Db
    {
        public:

            friend class SQL;

            Db();
            virtual ~Db();
            void Init();

            Db & Query( SQL &sql );
            Db & Query( const string & sql );
            bool setAutoCommit(bool);
            bool beginTransaction();
            bool commit();
            bool rollBack();
            DbResult *QueryResult( SQL &sql );
            DbResult *QueryResult( const string &sql );

            void QueryResultFree( const DbResult * dbr );

            int GetInsertId();
            int GetAffectedRows();

            int GetNumRows( const DbResult *res );

            Db &setConnectInfo( const string &ip , const string &user , const string &pwd );
            Db &setConnectInfo( const string &ip , const string &user , const string &pwd , unsigned short port );
            Db &setConnectInfo( const string &ip , const string &user , const string &pwd , const string &dbname );
            Db &setConnectInfo( const string &ip , const string &user , const string &pwd , const string &dbname , const unsigned short port  );
            Db &setConnectInfo( const char *ip , const char *user , const char *pwd , const char *dbname ) {
                string sip(ip) , suser(user), spwd(pwd),sdbname(dbname);
                return setConnectInfo( sip , suser , spwd , sdbname );
            }

            Db &Connect();
            Db &Connect( const string &ip , const unsigned short port , const string &user , const string &pwd );
            Db &Connect( const string &ip , const unsigned short port , const string &user , const string &pwd , const string &dbname );

            void Close();

        protected:
            MYSQL link;
        private:
             bitset<8> status;
             /*
                0 : 是否已经初始化
                1 : 是否已经连接
             */
             string _ip;
             unsigned short _port;
             string _user ;
             string _pwd ;
             string _dbname;
             DbResult *_result;
    };
}
#endif // DB_H
